from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from changliang import LUJING
from selenium.webdriver.common.by import By
wd = webdriver.Chrome(service=Service(LUJING))
import time
import json

#显示等待
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wd.get('http://127.0.0.1')

WebDriverWait(wd,3).until(EC.presence_of_element_located((By.ID,'username')))

# time.sleep(2)

# wd.add_cookie({'name':'sessionid','value':'34xrqtvehkw72nv310p3t05v92phwt3t'})

# wd.refresh()

time.sleep(1)

def load_cookie(wd:webdriver):
    try:
        with open('cok.json') as f:
            cookies = json.loads(f.read())

            # print(cookies[0]['value'])
        for i in cookies:
            print(i)
            wd.add_cookie(i)
        else:
            wd.refresh()
            
    except:
        print('没有找到cookie，需要正常登录')

load_cookie(wd)

print('执行到这里了')

try:
    wd.find_element(By.ID,'username').send_keys('byhy')
    wd.find_element(By.ID,'password').send_keys('88888888')

    wd.find_element(By.CSS_SELECTOR,'button').click()
    time.sleep(0.5)
    coks = wd.get_cookies()
except:
    pass

print(coks)

def save_cookie(wd:webdriver):
    cok = wd.get_cookies()
    with open('cok.json','w') as f:
        f.write(json.dumps(cok))


save_cookie(wd)

ele1 = wd.find_element(By.CSS_SELECTOR,'footer a')
# wd.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",ele1)
ele1.click()


time.sleep(2)
wd.quit()






